const {
  getUserLevel,
  getCourseInfo,
  setlike
} = require('../../../../api/api.js');
const app = getApp();
const {
  _showToast
} = require('../../../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    specialData: [],
    courseInfo: {},
    imgHost: '',
    vipLevel: null,
    buyPrice: 0,
    active: 0,
    detailTitle: {
      0: '课程介绍',
      1: '课程目录'
    },
    likeId: null,
    likeBackground: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      imgHost: app.img_host,
    })
    const {
      id
    } = options;
    this.setData({
      likeId: id
    })
    getCourseInfo(id).then(special => {
      console.log(special)
      this.setData({
        courseInfo: special.data
      })
      this.setData({
        buyPrice: special.data.price,
      })
      if (special.data.like_status) {
        this.setData({
          likeBackground: '#FF7A3F'
        })
      }
      if (special.data.look_auth == 1) {
        this.setData({
          buyPrice: 0
        })
      }
      this.getLevel(special)
      this.setData({
        specialData: special.data
      })
    }).catch(err => {
      console.log(err)
    })
  },
  //获取的用户的vip等级并处理返回
  getLevel(special) {
    getUserLevel().then(res => {
      //获取到用户的vip等级
      const user_level = res.level
      //如果为1的话就是vip
      if (user_level == 1) {
        this.setData({
          //计算出vip的优惠额度
          buyPrice: this.data.buyPrice * special.data.vip_discount
        })
        //如果为2的话就是svip
      } else if (user_level == 2) {
        this.setData({
          //计算出svip的优惠额度
          buyPrice: this.data.buyPrice * special.data.svip_discount
        })
      }
      this.setData({
        vipLevel: res.level
      })
    }).catch(err => {
      console.log(err)
    })
  },
  /**
   * 邀请提醒
   */
  toInvite() {
    _showToast("暂时不支持该功能");
  },
  /**
   * 列表切换到不同的课程中
   */
  change(e) {
    const index = e.detail.index + 1
    if (index === 2) {
      this.setData({
        active: this.data.active + 1
      })
    } else if (index === 1) {
      this.setData({
        active: this.data.active - 1
      })
    }
  },
  /**
   * 点击为喜欢
   */
  showLikes() {
    const id = this.data.likeId;
    setlike(id).then(res => {
      if (this.data.likeBackground) {
        this.setData({
          likeBackground: '',
          ['courseInfo.likes']: --this.data.courseInfo.likes
        })
      } else {
        this.setData({
          likeBackground: '#FF7A3F',
          ['courseInfo.likes']: ++this.data.courseInfo.likes
        })
      }
    }).catch(err => {
      console.log(err)
    })
  }
})